﻿using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Smart.Core;
using System.Threading.Tasks;

namespace Smart.SignalRServer
{
    public class SignalRHub : Hub
    {
        //在线用户
        private static Dictionary<string, List<string>> _connectionPool = new Dictionary<string, List<string>>();

        /// <summary>
        /// 组播
        /// </summary>
        /// <param name="groupId">组id</param>
        /// <param name="message">消息json字符串</param>
        public void sendByGroup(string messageJson)
        {
            MessageData messageData = CommonMethod.FromJsonTo<MessageData>(messageJson);
            messageData.fromConnnectId = Context.ConnectionId;
            try
            {
                messageData.dateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
                ex.Out();
            }
            Clients.Group(messageData.groupID).sendGroupMessage(messageData.ToJsonExt());
        }

        /// <summary>  
        /// 加入组
        /// </summary>  
        /// <param name="GroupId"></param>  
        public void joinGroup(string groupId)
        {
            Groups.Add(Context.ConnectionId, groupId);
        }

        /// <summary>  
        /// 离开组
        /// </summary>  
        /// <param name="GroupId"></param>  
        public void leaveGroup(string groupId)
        {
            Groups.Remove(Context.ConnectionId, groupId);
        }

        /// <summary>
        /// 发送私聊
        /// </summary>
        /// <param name="toConnnectId">接收方用户连接ID</param>
        /// <param name="message">内容</param>
        public void SendPrivateMessage(string messageJson)
        {
            MessageData messageData = CommonMethod.FromJsonTo<MessageData>(messageJson);
            try
            {
                var fromConnnectId = Context.ConnectionId;
                messageData.fromConnnectId = fromConnnectId;
                messageData.dateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Clients.Client(messageData.toConnnectId).receivePrivateMessage(messageJson.ToJsonExt());
            }
            catch (Exception ex)
            {
                ex.Out();
            }
            finally
            {
            }
        }

        /// <summary>
        /// 通知指定组
        /// </summary>
        /// <param name="groupIDs">组id数组</param>
        /// <param name="notifyContent">提醒内容</param>
        public void sendGroupNotify(List<string> groupIDs, string notifyContent)
        {
            Clients.Groups(groupIDs).receiveGroupNotify(notifyContent);
        }

        /// <summary>
        /// 通知全系统
        /// </summary>
        /// <param name="notifyContent">提醒内容</param>
        public void sendSystemNotify(string notifyContent)
        {
            Clients.Group("xzl").receiveGroupNotify(notifyContent);
        }

        /// <summary>  
        /// 离开组
        /// </summary>  
        /// <param name="groupId">组ID</param>  
        public void quitGroup(string groupId)
        {
            Groups.Remove(Context.ConnectionId, groupId);
        }

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="userID">用户ID</param>
        public dynamic connect(string userID)
        {
            Common.WriteLog(userID);
            if (string.IsNullOrEmpty(userID))
            {
                return new { error = 1, message = "参数userID不能为空" };
            }
            if (_connectionPool.ContainsKey(userID))
            {
                if (!_connectionPool[userID].Contains(Context.ConnectionId))
                {
                    _connectionPool[userID].Add(Context.ConnectionId);
                    joinGroup("xzl");
                }
            }
            else
            {
                _connectionPool.Add(userID, new List<string>() { Context.ConnectionId });
                joinGroup("xzl");
            }
            return new { error = 0 };
        }

        /// <summary>
        /// 按用户ID发送通知
        /// </summary>
        /// <param name="userIDs">接收方用户ID数组</param>
        /// <param name="message">通知内容</param>
        public void sendNotity(string[] userIDs, string notifyContent)
        {
            Common.WriteLog(notifyContent);
            foreach (var userID in userIDs)
            {
                if (_connectionPool.ContainsKey(userID))
                {
                    Clients.Clients(_connectionPool[userID]).receiveNotity(notifyContent);
                }
            }
        }

        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            foreach (var connect in _connectionPool)
            {
                if (connect.Value.Contains(Context.ConnectionId))
                {
                    connect.Value.Remove(Context.ConnectionId);
                    if (connect.Value.Count == 0)
                    {
                        _connectionPool.Remove(connect.Key);
                    }
                    break;
                }
            }
            return base.OnDisconnected(stopCalled);
        }
        //public override Task OnDisconnected()
        //{
        //    get
        //    {
        //        foreach (var connect in _connectionPool)
        //        {
        //            if (connect.Value.Contains(Context.ConnectionId))
        //            {
        //                connect.Value.Remove(Context.ConnectionId);
        //                if (connect.Value.Count == 0)
        //                {
        //                    _connectionPool.Remove(connect.Key);
        //                }
        //                break;
        //            }
        //        }
        //        return base.OnDisconnected();
        //    }
        //}
    }

    public class UserData
    {
        /// <summary>
        /// 连接ID
        /// </summary>
        public string ConnectionID { get; set; }
        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserID { get; set; }
    }

    public class MessageData
    {
        public string fromConnnectId { get; set; }
        public string toConnnectId { get; set; }
        public string toUserID { get; set; }
        public string groupID { get; set; }
        public string message { get; set; }
        public string userID { get; set; }
        public string photoPath { get; set; }
        public string dateTime { get; set; }
        public string userName { get; set; }
        public string userType { get; set; }
    }
}